/**
 * 
 */
package t4j.annotations.datebase;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class TableCreator {

	private static String getConstraints(Constraints con) {
		String constraints = "";
		if (!con.allowNull())
			constraints += " NOT NULL";
		if (con.primaryKey())
			constraints += " PRIMARY KEY";
		if (con.unique())
			constraints += " UNIQUE";

		return constraints;

	}

	public static void main(String[] args) throws Exception {
		args = new String[]{"t4j.annotations.datebase.Member"};
		
		for (String className : args) {
			Class<?> cl = Class.forName(className);
			DBtable dbTable = cl.getAnnotation(DBtable.class);// 获取类的注解
			if (dbTable == null) {
				System.out.println("No DBTable annotations in class " + className);
				continue;
			}

			String tableName = dbTable.name();//获取类注解的类名称

			if (tableName.length() < 1)
				tableName = cl.getName().toUpperCase();

			List<String> columnDefs = new ArrayList<String>();

			// 获取类的域
			for (Field field : cl.getDeclaredFields()) {
				String columnName = null;
				Annotation[] anns = field.getDeclaredAnnotations();// 获取域的注解

				if (anns.length < 1)
					continue; // 域没有注解，则跳出到下一个循环

				if (anns[0] instanceof SQLInteger) {
					SQLInteger sInt = (SQLInteger) anns[0];

					//如果注解里面的name元素为空
					if (sInt.name().length() < 1)
						columnName = field.getName().toUpperCase();// 使用域的名字
					else
						columnName = sInt.name();//使用name元素

					columnDefs.add(columnName + " INT" + getConstraints(sInt.constraints()));//获取嵌套的constraints元素，去作处理
				}

				if (anns[0] instanceof SQLString) {
					SQLString sString = (SQLString) anns[0];

					if (sString.name().length() < 1)
						columnName = field.getName().toUpperCase();
					else
						columnName = sString.name();

					columnDefs.add(columnName + " VARCHAR(" + sString.value() + ")"
							+ getConstraints(sString.constraints()));

				}
				
				StringBuilder createCommand = new StringBuilder("CREATE TABLE " + tableName + "(");

				for (String columnDef : columnDefs)
					createCommand.append("\n     " + columnDef + ",");

				String tableCreate = createCommand.substring(0, createCommand.length() - 1) + ");";

				System.out.println("Table Creation SQL for " + className + " is :\n" + tableCreate);
			}
		}
	}

}
